# import requests
# from django.conf import settings
# from .models import ThirdParty
# from django.contrib.auth.models import User
#
#
# class ThirdPartyLoginFactory:
#     @staticmethod
#     def create_login_instance(login_type):
#         if login_type == '3':  # 钉钉登录
#             return DingTalkLogin()
#         # 可以添加其他第三方登录类型
#         return None
#
#
# class DingTalkLogin:
#     def get_authorize_url(self):
#         authorize_url = f"https://login.dingtalk.com/oauth2/auth?redirect_uri={settings.DINGTALK_REDIRECT_URI}&response_type=code&client_id={settings.DINGTALK_APP_KEY}&scope=openid&prompt=consent"
#         return authorize_url
#
#     def get_access_token(self, code):
#         token_url = "https://api.dingtalk.com/v1.0/oauth2/userAccessToken"
#         headers = {
#             'Content-Type': 'application/json'
#         }
#         data = {
#             "clientId": settings.DINGTALK_APP_KEY,
#             "clientSecret": settings.DINGTALK_APP_SECRET,
#             "code": code,
#             "grantType": "authorization_code"
#         }
#         response = requests.post(token_url, headers=headers, json=data)
#         token_data = response.json()
#         return token_data.get('accessToken')
#
#     def get_user_info(self, access_token):
#         user_info_url = f"https://api.dingtalk.com/v1.0/contact/users/me?accessToken={access_token}"
#         user_info_response = requests.get(user_info_url)
#         user_info = user_info_response.json()
#         return user_info
#
#     def save_user_info(self, user_info, user):
#         dingtalk_uid = user_info.get('unionId')
#         if dingtalk_uid:
#             third_party_record = ThirdParty.objects.filter(types='3', uid=dingtalk_uid).first()
#             if not third_party_record:
#                 ThirdParty.objects.create(
#                     types='3',
#                     uid=dingtalk_uid,
#                     userid=user
#                 )
#             else:
#                 third_party_record.userid = user
#                 third_party_record.save()

#
# from abc import ABC,abstractmethod
# from user import models
# from utils.tooljwt import myjwt
# from urllib.parse import quote
# import requests
# import time
#
#
# def get_user(phone,uid,types):
#     user = models.ThirdParty.objects.filter(uid=uid).first()
#     if user:
#         userdata = {"id": user.userid_id, "phone": user.userid.phone, 'exp': int(time.time()) + 60 * 60 * 24}
#     else:
#         user = models.User.objects.create(
#             phone=phone,
#             is_vip=0,
#             gold=0,
#             income=0,
#         )
#         models.ThirdParty.objects.create(
#             types=types,
#             uid=uid,
#             userid_id=user.id,
#         )
#         userdata = {"id": user.id, "phone": user.phone, 'exp': int(time.time()) + 60 * 60 * 24}
#     token = myjwt.jwt_encode(userdata)
#     userdata['exp'] = int(time.time()) + 60 * 60 * 24 * 3
#     retoken = myjwt.jwt_encode(userdata)
#     data = {'userid':user.id,'token':token,'retoken':retoken}
#     return data
#
#
# # 抽象工厂
# class Product(ABC):
#     @abstractmethod
#     def geturl(self):
#         pass
#     @abstractmethod
#     def callback(self,authCode,types):
#         pass
#
#
# # 具体工厂
# class DingDingLogin(Product):
#     def __init__(self):
#         self.params = [
#             f"redirect_uri={quote('http://127.0.0.1:5173/')}",
#             "response_type=code",
#             "client_id=dingq04kegs2mhy0ho64",
#             "scope=openid",
#             "prompt=consent"
#         ]
#
#         self.url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(self.params))
#
#     def geturl(self):
#         return self.url
#
#     def callback(self,authCode,type):
#         data = {
#             "clientId": "dingq04kegs2mhy0ho64",
#             "clientSecret": "a_5qWg2FqFrgQnmaa93Wi9cwOgi7L2nXnCwmY22u98orhgX53criMMvpOVy8Ugh3",
#             "code": authCode,
#             "grantType": "authorization_code"
#         }
#         resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
#         accessToken = resp.get('accessToken')
#
#         # 根据accessToken获取用户信息
#         headers = {"x-acs-dingtalk-access-token": accessToken}
#         resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
#
#         if resp.get('stateCode') != '86':
#             return 4000
#         phone = resp.get('phone')
#         uid = resp.get('openId')
#         data = get_user(phone,uid,type)
#         return data
#
#
# class Factory():
#     def create_factory(self, params):
#         if params == '3':
#             return DingDingLogin()
#         # 可以抛出异常或者返回错误信息，这里选择返回 None 并在视图中处理
#         return None
#
#
# fact = Factory()


from abc import ABC,abstractmethod

class SFlogin(ABC):
    @abstractmethod
    def geturl(self):
        pass

    @abstractmethod
    def callback(self):
        pass


class Dingding(SFlogin):
    def __init__(self) -> None:
        self.client_id = "dingq04kegs2mhy0ho64"
        self.callbackurl = "http://127.0.0.1:5173/callback/"

    def geturl(self):
        return 'http://login.dingding.talk.com/aut'

    def callback(self):
        pass


class Weibo(SFlogin):
    def __init__(self) -> None:
        pass

    def geturl(self):
        return 'http://weibo.com/aut'

    def callback(self):
        pass


class Factory():
    def get_login_class(self, types):
        if types == '3':
            return Dingding()


fact = Factory()

# from abc import ABC, abstractmethod
# import time
# import requests
# from rest_framework.response import Response
# from .models import User, ThirdParty
# from .ser import UserSer, Third
# from utils.tooljwt import myjwt
# class Product(ABC):
#     @abstractmethod
#     def geturl(self):
#         pass
#
#     @abstractmethod
#     def callback(self,request):
#         pass
#
#
# class Dingding(Product):
#     def __init__(self) -> None:
#         self.api_key = 'dingbpqefqx48hfpmpni'
#         self.api_secret = '0GKAU8YydIE0l1jBF0M-WImM4IJ0_qhTY8H-L1Hc4u6wROBOnulzAJClUOPuI_Qs'
#
#     def geturl(self):
#         from urllib.parse import quote
#         params = [
#             f"redirect_uri={quote('http://127.0.0.1:8000/login/dingtalkcallback/?type=ding')}",
#             "response_type=code",
#             "client_id=dingbpqefqx48hfpmpni",  # 这里添加逗号
#             "scope=openid",
#             "prompt=consent"
#         ]
#         url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
#         return url
#
#     def callback(self,request):  # 接收 request 对象作为参数
#         authCode = request.query_params.get('code')
#         # 根据 authCode 获取用户 accessToken
#         print(authCode)
#         data = {
#             "clientId": self.api_key,
#             "clientSecret": self.api_secret,
#             "code": authCode,
#             "grantType": "authorization_code"
#         }
#         resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
#         accessToken = resp.get('accessToken')
#
#         # 根据 accessToken 获取用户信息
#         headers = {"x-acs-dingtalk-access-token": accessToken}
#         resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me',headers=headers).json()
#         name = resp.get('nick')
#         uid = resp.get('openId')
#         phone = resp.get('mobile')
#         print("wwww")
#         print(name)
#         print(uid)
#         print(phone)
#         # 登录，写入三方登录表和用户表
#         sfl = ThirdParty.objects.filter(uid=uid, types=1).first()
#         if not sfl:
#             # 写入用户表
#             # 手机号用户存在直接绑定,不存在注册新用户
#             user = User.objects.filter(phone=phone).first()
#             if not user:
#                 userinfo = {
#                     "name": name,
#                     "phone": phone,
#                 }
#                 us = UserSer(data=userinfo)
#                 if us.is_valid():
#                     user = us.save()
#                 else:
#                     # 将错误信息转换为字符串
#                     return Response({"code": 10003, "msg": str(us.errors)})
#             # 写入三方登录表
#             sfinfo = {
#                 "types": 1,
#                 "token": accessToken,
#                 "uid": uid,
#                 "userid": user.id
#             }
#             sfs = Third(data=sfinfo)
#             if sfs.is_valid():
#                 sfs.save()
#             else:
#                 # 将错误信息转换为字符串
#                 return Response({"code": 10002, "msg": str(sfs.errors)})
#         else:
#             user = sfl.userid
#             sfl.token = accessToken
#             sfl.save()
#         # 生成 jwt token 并返回前端
#         print("eeeeeeee")
#         payload = {"userid": user.id, "username": user.username, "exp": int(time.time()) + 60 * 60 * 2}
#         print(payload)
#         token = myjwt.jwt_encode(payload)
#         print(token)
#         payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
#         refreshToken = myjwt.jwt_encode(payload)
#         query = [f"userid={payload['userid']}", f"username={payload['username']}", f"token={token}",
#                  f"refreshToken={refreshToken}"]
#         # url = f"{request.query_params.get('redirect_uri')}?{('&'.join(query))}"
#         url=f'http://localhost:5173/own?{"&".join(query)}'
#         return url
#
#     # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjYsInVzZXJuYW1lIjoiWmI4blBmM2oiLCJleHAiOjE3MzcyMTMwOTN9.SElauvh1jVStR2RjLED8pKO_8JnkbiiVQmitlBtyjd8 & refreshToken = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjYsInVzZXJuYW1lIjoiWmI4blBmM2oiLCJleHAiOjE3MzczNzg2OTN9.ESL_VctdSUeS9WYgko - CLGIgpZekhRgJgOnNFTfdKwg
# class Factory():
#     def create_factory(self,params):
#         if params == 'ding':
#             return Dingding()
# factory = Factory()


#
# from abc import ABC, abstractmethod
# from urllib.parse import quote
# from django.http import HttpResponseRedirect
# from rest_framework.response import Response
# from user.models import ThirdParty, User
# from user.ser import UserSer, Third
# from utils.tooljwt import myjwt
# import requests
# import time
#
#
# class Product(ABC):
#     @abstractmethod
#     def geturl(self):
#         pass
#
#     @abstractmethod
#     def callback(self, request):
#         pass
#
#
# class SfDingDing(Product):
#
#     def __init__(self):
#         self.params = [
#             f"redirect_uri={quote('http://127.0.0.1:5173/')}",  # 重定向URI，进行了URL编码
#             "response_type=code",  # 响应类型为授权码
#             "client_id=dingq04kegs2mhy0ho64",  # 钉钉应用的客户端ID
#             "scope=openid",  # 授权范围为获取用户的openID
#             "prompt=consent"  # 提示用户进行授权确认
#         ]
#         self.myjwt = myjwt
#
#     def geturl(self):
#         url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(self.params))
#         return url
#
#     def callback(self, request):
#         authCode = request.query_params.get('code')
#         print(authCode)
#         data = {
#             "clientId": "dingq04kegs2mhy0ho64",
#             "clientSecret": "a_5qWg2FqFrgQnmaa93Wi9cwOgi7L2nXnCwmY22u98orhgX53criMMvpOVy8Ugh3",
#             "code": authCode,
#             "grantType": "authorization_code"
#         }
#         resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
#         print(resp)
#         accessToken = resp.get('accessToken')
#
#         # 根据accessToken获取用户信息
#         headers = {"x-acs-dingtalk-access-token": accessToken}
#         resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
#         username = resp.get('username')
#         uid = resp.get('openId')
#         phone = resp.get('phone')
#         print(phone)
#
#         # 登录，写入三方登录表和用户表
#         sfl = ThirdParty.objects.filter(uid=uid).first()
#         if not sfl:
#             # 写入用户表
#             # 手机号用户存在直接绑定,不存在注册新用户
#             user = User.objects.filter(phone=phone).first()
#             # print(user)
#             if not user:
#                 userinfo = {
#                     "username": username,
#                     "phone": phone,
#                 }
#                 us = UserSer(data=userinfo)
#                 if us.is_valid():
#                     user = us.save()
#                 else:
#                     # "msg": tostr(us.errors)
#                     return Response({"code": 10001})
#             # 写入三方登录表
#             print(uid)
#             sfinfo = {
#                 "uid": uid,
#                 "userid": user.id
#             }
#             sfs = Third(data=sfinfo)
#             if sfs.is_valid():
#                 sfs.save()
#             else:
#                 # "msg": tostr(sfs.errors)
#                 return Response({"code": 10001})
#         else:
#             user = sfl.userid
#             sfl.save()
#
#         # 生成jwt token并返回前端
#         payload = {"id": user.id, "phone": user.phone, "exp": int(time.time()) + 60 * 60 * 2}
#         token = self.myjwt.jwt_encode(payload)
#         payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
#         retoken = self.myjwt.jwt_encode(payload)
#         query = [f"userid={payload['id']}", f"phone={payload['phone']}", f"token={token}",
#                  f"retoken={retoken}"]
#         return f'http://localhost:8080/?{"&".join(query)}'
#         # return query
#
#
# s = SfDingDing()
#
#
# class Factory():
#     def create_factory(self, params):
#         # getattr  setattr
#         if params == '3':
#             return SfDingDing()
#
# fact = Factory()